<template>
  <div>
    <!-- 下拉框 -->
    <el-row type="flex" justify="end">
      <el-select v-model="year" size="small" @change="dateChangeFn">
        <el-option v-for="item in yearList" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="month" size="small" @change="dateChangeFn">
        <el-option v-for="item in 12" :key="item" :label="item" :value="item" />
      </el-select>
    </el-row>

    <!-- 日历布局 -->
    <el-calendar v-if="showCalendar" v-model="curDate">
      <!-- 自定义内容 -->
      <template v-slot:dateCell="{date, data}" class="content">
        <!--
          date:单元格代表的日期
          data:{ type, isSelected, day}
            day :标识格式化日期
         -->
        <div class="date-content">
          <span class="text"> {{ data.day | forDateDay }}</span>
          <span v-if="isWeek(date)" class="rest">休</span>
        </div>
      </template>
    </el-calendar>
  </div>
</template>

<script>
const curDate = new Date() // 获取日期
const year = curDate.getFullYear() // 获取年
const month = curDate.getMonth() + 1 // 获取月
const yearList = []
for (let i = 0; i < 11; i++) {
  yearList.push(year - 5 + i)
}
export default {
  filters: {
    forDateDay(val) {
      // 格式化日期
      return Number(val.split('-')[2])
    }

  },
  data() {
    return {
      curDate,
      year,
      month,
      yearList,
      showCalendar: true
    }
  },
  watch: {
    /* 日历组件点击 关联 下拉框年月 */
    curDate(date) {
      this.year = date.getFullYear()
      this.month = date.getMonth() + 1
    },
    /**
     * bug:日历组件在切换语言的时候不会实时更新
     * 解决办法,在切换语言的时候销毁组件再重新创建
     * 使用v-if来控制销毁和创建,由于组件的销毁和创建是异步
     * 需要配置next
     */
    '$i18n.locale'(lang) {
      console.log(lang)
      this.showCalendar = false
      this.$nextTick(() => {
        this.showCalendar = true
      })
    }
  },
  methods: {
    /* 下拉框选择年月 关联 日历组件 */
    dateChangeFn() {
      // console.log(this.year, this.month)
      this.curDate = new Date(`${this.year}-${this.month}`) // 获取日期
    },
    isWeek(date) {
      // 根据传入的日期是否为周末, 返回 true / false
      return date.getDay() === 6 || date.getDay() === 0
    }
  }

}
</script>

<style  scoped>
 /deep/ .el-calendar-day {
  height:  auto;
 }
 /deep/ .el-calendar-table__row td,/deep/ .el-calendar-table tr td:first-child,  /deep/ .el-calendar-table__row td.prev{
  border:none;
 }
.date-content {
  height: 40px;
  text-align: center;
  line-height: 40px;
  font-size: 14px;
}
.date-content .rest {
  color: #fff;
  border-radius: 50%;
  background: rgb(250, 124, 77);
  width: 20px;
  height: 20px;
  line-height: 20px;
  display: inline-block;
  font-size: 12px;
  margin-left: 10px;
}
.date-content .text{
  width: 20px;
  height: 20px;
  line-height: 20px;
 display: inline-block;

}
 /deep/ .el-calendar-table td.is-selected .text{
   background: #409eff;
   color: #fff;
   border-radius: 50%;
 }
 /deep/ .el-calendar__header {
   display: none
 }
</style>

